#!/bin/sh

if [ -n "$(uci -q get dhcp.odhcpd)" ]; then
	local commit
	local hostsfile

	commit=0

	if [ -z "$(uci -q get dhcp.odhcpd.piofolder)" ]; then
		uci set dhcp.odhcpd.piofolder=/tmp/odhcpd-piofolder
		commit=1
	fi

	if [ -n "$(uci -q get dhcp.odhcpd.legacy)" ]; then
		uci delete dhcp.odhcpd.legacy
		commit=1
	fi

	hostsfile=$(uci -q get dhcp.odhcpd.hostsfile)
	if [ -n "$hostsfile" ]; then
		uci delete dhcp.odhcpd.hostsfile
		uci set dhcp.odhcpd.hostsdir="$(dirname $hostsfile)"
		commit=1
	elif [ -z "$(uci -q get dhcp.odhcpd.hostsdir)" ]; then
		uci set dhcp.odhcpd.hostsdir=/tmp/hosts
		commit=1
	fi

	if [ "$(uci -q get dhcp.odhcpd.leasefile)" == "/tmp/hosts/odhcpd" ]; then
		uci set dhcp.odhcpd.leasefile=/tmp/odhcpd.leases
		commit=1
	fi

	[ "$commit" -eq 1 ] && uci commit dhcp

	exit 0
fi

touch /etc/config/dhcp

. /usr/share/libubox/jshn.sh

json_load "$(cat /etc/board.json)"
json_select network
json_select lan
json_get_vars protocol
json_select ..
json_select ..

ODHCPDONLY=0
V4MODE=disabled
V6MODE=disabled

[ -e /usr/sbin/dnsmasq ] || ODHCPDONLY=1

case "$protocol" in
# only enable server mode on statically addressed lan ports
"static")
	V4MODE=server
	[ -e /proc/sys/net/ipv6 ] && V6MODE=server
	;;
esac

uci -q get dhcp.lan || {
uci batch <<EOF
set dhcp.lan=dhcp
set dhcp.lan.interface='lan'
set dhcp.lan.start='100'
set dhcp.lan.limit='150'
set dhcp.lan.leasetime='12h'
set dhcp.lan.domain='lan'
EOF
}

uci batch <<EOF
set dhcp.odhcpd=odhcpd
set dhcp.odhcpd.maindhcp=$ODHCPDONLY
set dhcp.odhcpd.leasefile=/tmp/odhcpd.leases
set dhcp.odhcpd.leasetrigger=/usr/sbin/odhcpd-update
set dhcp.odhcpd.loglevel=4
set dhcp.odhcpd.piofolder=/tmp/odhcpd-piofolder
set dhcp.odhcpd.hostsdir=/tmp/hosts
set dhcp.lan.dhcpv4=$V4MODE
set dhcp.lan.dhcpv6=disabled
set dhcp.lan.ra=$V6MODE
set dhcp.lan.ra_slaac=1
set dhcp.lan.max_preferred_lifetime=2700
set dhcp.lan.max_valid_lifetime=5400
commit dhcp
EOF
